package cvo.chess.client.entities.chessboard;

import cvo.chess.client.entities.game.IChessboard;

/**
 * 
 * @author Stijn.Van.Antwerpen
 *
 * A chessboardCoordinate is used to contain the position on a chessboard. 
 */
public class ChessboardCoordinate implements IChessboardCoordinate {
	
	public static char LEFT_COL_CHAR = 'A';
	public static char BOTTOM_ROW_CHAR = '1';
	
	private IChessboard board;
	private int row, col;
	
	public ChessboardCoordinate(IChessboard board, String A1notation){
		this.board = board;
		setA1Notation(A1notation);
	}
	
	/* (non-Javadoc)
	 * @see cvo.chess.client.entities.chessboard.IChessBoardCoordinate#setA1Notation(java.lang.String)
	 */
	@Override
	public void setA1Notation(String a1notation) {
		if(validateA1Notation(a1notation)){
			char firstChar = a1notation.charAt(0);
			char secondChar = a1notation.charAt(1);
			this.col = (firstChar - LEFT_COL_CHAR);
			this.row = (board.getHeight() - 1) - (secondChar - BOTTOM_ROW_CHAR);	
		}else
		{
			//TODO: Exception
		}
	}
	
	/* (non-Javadoc)
	 * @see cvo.chess.client.entities.chessboard.IChessBoardCoordinate#getA1Notation()
	 */
	@Override
	public String getA1Notation(){
		return new StringBuilder()
			.append((char)(LEFT_COL_CHAR +  this.col)) 
			.append((char)(BOTTOM_ROW_CHAR + (board.getHeight() -1) - this.row))
			.toString();
	}
	

	private boolean validateA1Notation(String a1notation) {
		// TODO: validate string 
		return true;
	}

	public ChessboardCoordinate(IChessboard board,  int col, int row)
	{
		this.board = board;
		this.row = row;
		this.col = col;
	}
	
	/* (non-Javadoc)
	 * @see cvo.chess.client.entities.chessboard.IChessBoardCoordinate#getNummericPosition()
	 */
	@Override
	public int getNummericPosition()
	{
		return this.col  + (this.row * this.board.getWidth());
	}

	/* (non-Javadoc)
	 * @see cvo.chess.client.entities.chessboard.IChessBoardCoordinate#getRow()
	 */
	@Override
	public int getRow() {
		return this.row;
	}

	/* (non-Javadoc)
	 * @see cvo.chess.client.entities.chessboard.IChessBoardCoordinate#getCol()
	 */
	@Override
	public int getCol() {
		return this.col;
	}
	
	@Override
	public String toString(){
		return this.getA1Notation() + " (col:" + this.col + ", row:" + this.row + ") position:" + this.getNummericPosition();
	}
	
	@Override
	public boolean equals(Object obj){
		if(!(obj instanceof ChessboardCoordinate))
			return false;
		//instanceof return false when null, so check for null is not requiered
		
		ChessboardCoordinate other = (ChessboardCoordinate)obj;
		
		//Will only be equal if coordinates of the same board.
		return this.board.equals(other.board) &&				
				(other.getNummericPosition() == this.getNummericPosition());
	}
	
	@Override
	public int hashCode(){
		return this.board.hashCode()
			+ this.col
			+ this.row;
				
	}
	
//	public void setNummericPosition(Integer n)
//	{
//			
//	}
}
